package com.usian.common.exception;

import com.usian.common.CommonException;
import com.usian.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 全局异常处理
 */
@ControllerAdvice //将报异常的controller的传到此类 ，增强controller
//aop的应用  ：面向切面 ，在不修改源代码的情况，对代码进行增强    ***************
public class BaseExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result error(HttpServletRequest request, HttpServletResponse response,
                        Exception e) throws IOException {e.printStackTrace(); //打印输出异常信息
        if (e.getClass() == CommonException.class) {
            CommonException ce = (CommonException) e;
            return new Result(ce.getCode());
        } else {
            return Result.ERROR();
        }
    }
}
